<?php

namespace mpend\modules\member\models;

use Yii;
use common\base\Model;
use common\logics\SmsCaptchaForm;
use common\models\member\Member;
use common\models\member\MemberData;
use common\models\member\MemberDataPersonal;

class MemberApplyForm extends Model {

    /**
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @var integer 会员类型ID
     */
    public $type_id;

    /**
     * @var integer 会员ID
     */
    public $member_id = 0;

    /**
     * @var string 真实姓名
     */
    public $realname;

    /**
     * @var string 身份证号
     */
    public $idcardno;

    /**
     * @var string 手机号
     */
    public $mobile;

    /**
     * @var string 个人照片
     */
    public $photo;

    /**
     * @var string 身份证正面
     */
    public $passport_front;

    /**
     * @var string 身份证反面
     */
    public $passport_reverse;

    /**
     * @var string 省份
     */
    public $province;

    /**
     * @var string 城市
     */
    public $city;

    /**
     * @var string 区县
     */
    public $district;

    /**
     * @var string 详细地址
     */
    public $address_detail;

    /**
     * @var string 地区编码，通过省市区选择获取
     */
    public $area_code;

    /**
     * @var string 邮政编码
     */
    public $postal_code;

    /**
     * @var string 职业
     */
    public $occupation;

    /**
     * @var string 学历
     */
    public $qualification;

    /**
     * @var string 单位/学校
     */
    public $organization;

    /**
     * @var string 月收入
     */
    public $income;

    /**
     * @var string 短信验证码
     */
    public $code;

    /**
     * @name $_model
     */
    private $_model = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['member_id', 'user_id', 'type_id'], 'integer'],
            [['realname', 'idcardno', 'mobile', 'province', 'city', 'district', 'area_code', 'address_detail'], 'required'],
            [['income'], 'number'],
            [['occupation', 'qualification', 'organization', 'photo', 'passport_front', 'passport_reverse'], 'string'],
            [['area_code', 'postal_code', 'code'], 'string', 'max' => 6],
            ['member_id', 'validateModel'],
            ['mobile', '\common\validators\MobileValidator'],
            ['idcardno', '\common\validators\IdcardValidator'],
            ['code', 'validateCaptchaCode'],
        ];
    }

    /**
     * 校验会员
     */
    public function validateModel($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = null;
        if ($this->$attribute) {
            $model = Member::findOne($this->$attribute);
        }
        if (!$model) {
            $model = new Member();
        }
        $this->_model = $model;
    }

    /**
     * 校验短信验证码
     */
    public function validateCaptchaCode($attribute) {
        if ($this->hasErrors() && !YII_DEBUG) {
            return;
        }
        $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_MEMBER . '_' . $this->mobile);
        if ($captcha == false) {
            $this->addError($attribute, $this->getAttributeLabel($attribute) . '已过期');
        } elseif ($captcha !== $this->$attribute) {
            $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
        }
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('提交失败');
        }
        //会员
        $model = $this->_model;
        $model->attributes = [
            'user_id' => $this->user_id,
            'type_id' => $this->type_id,
            'audit_status' => Member::AUDIT_STATUS_SUBMIT,
            'status' => Member::STATUS_ACTIVE,
        ];
        //会员基础资料
        $data = $model->data;
        if (!$data) {
            $data = new MemberData();
        }
        $data->attributes = [
            'user_id' => $this->user_id,
            'realname' => $this->realname,
            'idcardno' => $this->idcardno,
            'mobile' => $this->mobile,
            'photo' => $this->photo,
            'passport_front' => $this->passport_front,
            'passport_reverse' => $this->passport_reverse,
            'status' => MemberData::STATUS_DEFAULT,
        ];
        //会员个人资料
        $personal = $model->personal;
        if (!$personal) {
            $personal = new MemberDataPersonal();
        }
        $personal->attributes = [
            'province' => $this->province,
            'city' => $this->city,
            'district' => $this->district,
            'address_detail' => $this->address_detail,
            'area_code' => $this->area_code,
            'postal_code' => $this->postal_code,
            'organization' => $this->organization,
            'qualification' => $this->qualification,
            'occupation' => $this->occupation,
            'income' => $this->income,
            'status' => MemberDataPersonal::STATUS_DEFAULT,
        ];

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('会员信息创建失败');
            }
            $data->member_id = $model->id;
            if (!$data->save()) {
                throw new Exception('会员基本信息保存失败');
            }
            $personal->member_id = $model->id;
            if (!$personal->save()) {
                throw new Exception('会员个人信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError('', $e);
        }
        Yii::$app->cache->delete('captcha_' . SmsCaptchaForm::SCOPE_MEMBER . '_' . $this->mobile);
        return true;
    }

}
